package com.peter.proxy.hkgolden.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.peter.proxy.hkgolden.api.ContentService;
import com.peter.proxy.hkgolden.api.Topic;

@Singleton
@SuppressWarnings("serial")
public class TopicServlet extends HttpServlet {

	@Inject
	public void setInjector(Injector injector) {
		this.injector = injector;
	}

	private Injector injector;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.debug("doGet()");

		long start = System.currentTimeMillis();

		int id = 0;
		int page = 1;
		try {
			id = Integer.parseInt(req.getParameter("id"));
			try {
				page = Integer.parseInt(req.getParameter("p"));
			} catch (Exception e) {
			}

			ContentService contentService = injector
					.getInstance(ContentService.class);
			logger.trace("contentService = {}", contentService);

			Topic topic = contentService.messages(id, page);
			logger.trace("messages.size() = {}", topic.getMessages().size());

			req.setAttribute("topic", topic);
			req.setAttribute("usedTime", System.currentTimeMillis() - start);
			req.getRequestDispatcher("/topic.jsp").forward(req, resp);
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
